<template>
    <div class="app-container">



        <div class="app-page">
            <el-form class="search-form" :model="form" :rules="rules" ref="companyRef" :inline="true" label-width="160px">
                <div class="app-item">
                    <div class="app-title">助贷方公司信息</div>
                    <div class="app-cont">
                        <el-form-item class="form-item" label="营业执照" prop="license">
                            <el-upload class="upload-demo avatar-uploader" action="#" :show-file-list="false"
                                :http-request="($event) => { httpRequest($event, 1) }">
                                <el-avatar v-if="form.license" :src="checkUrl(form.license)" shape="square" :size="178"
                                    fit="contain" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>

                        </el-form-item>
                        <el-form-item class="form-item v50" label="公司名称" prop="companyName">
                            <el-input class="search-vitem" v-model="form.companyName" placeholder="公司名称" clearable />
                        </el-form-item>
                        <!-- <el-form-item class="form-item v50" label="公司简称(英文)" prop="creditCode">
                            <el-input class="search-vitem" v-model="form.creditCode" placeholder="公司简称(英文)" clearable />
                        </el-form-item> -->
                        <el-form-item class="form-item v50" label="统一社会信用代码" prop="creditCode">
                            <el-input class="search-vitem" v-model="form.creditCode" placeholder="统一社会信用代码" clearable />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="成立日期" prop="establishmentDate">
                            <el-date-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="search-vitem"
                                v-model="form.establishmentDate" type="date" placeholder="成立日期" />
                        </el-form-item>
                        <el-form-item class="form-item" label="公司地址" prop="citycode">
                            <el-cascader v-model="form.citycode" :options="cityOpt" :props="CascaderProps" />
                            <el-input class="search-vitem v-address2" v-model="form.address" placeholder="请输入详细地址"
                                clearable />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="公司性质" prop="companyNature">
                            <el-select class="search-vitem" v-model="form.companyNature" clearable filterable
                                placeholder="公司性质">
                                <el-option v-for="(item, index) in companyNatureArr" :key="index" :label="item.dictLabel"
                                    :value="item.dictValue">
                                    {{ item.dictLabel }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item class="form-item v50" label="机构类型" prop="types">
                            <el-select class="search-vitem" v-model="form.types" clearable filterable
                                placeholder="机构类型">
                                <el-option v-for="(item, index) in orgTypeArr" :key="index" :label="item.dictLabel"
                                    :value="item.dictValue">
                                    {{ item.dictLabel }}
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item class="form-item v50" label="营业执照有效期" prop="licensePeriod">
                            <el-date-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="search-vitem"
                                v-model="form.licensePeriod" type="date" placeholder="若为长期，则不填写" />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="开业状态" prop="companyStatus">
                            <el-select class="search-vitem" v-model="form.companyStatus" clearable filterable
                                placeholder="开业状态">
                                <el-option v-for="(item, index) in companyStatusArr" :key="index" :label="item.dictLabel"
                                    :value="item.dictValue">
                                    {{ item.dictLabel }}
                                </el-option>
                            </el-select>
                        </el-form-item>

                    </div>
                </div>

                <div class="app-item">
                    <div class="app-title">法人信息</div>
                    <div class="app-cont">
                        <el-form-item class="form-item v50" label="法人身份证正面" prop="idcFront">
                            <el-upload class="upload-demo avatar-uploader" action="#" :show-file-list="false"
                                :http-request="($event) => { httpRequest($event, 2) }">
                                <el-avatar v-if="form.idcFront" :src="checkUrl(form.idcFront)" shape="square" :size="178"
                                    fit="contain" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>

                        </el-form-item>


                        <el-form-item class="form-item v50" label="法人身份证反面" prop="idcBack">
                            <el-upload class="upload-demo avatar-uploader" action="#" :show-file-list="false"
                                :http-request="($event) => { httpRequest($event, 3) }">
                                <el-avatar v-if="form.idcBack" :src="checkUrl(form.idcBack)" shape="square" :size="178"
                                    fit="contain" />
                                <el-icon v-else class="avatar-uploader-icon">
                                    <Plus />
                                </el-icon>
                            </el-upload>

                        </el-form-item>

                        <el-form-item class="form-item v50" label="法人姓名" prop="corporationName">
                            <el-input class="search-vitem" v-model="form.corporationName" placeholder="法人姓名" clearable />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="法人身份证号码" prop="corporationIdc">
                            <el-input class="search-vitem" v-model="form.corporationIdc" placeholder="法人身份证号码" clearable />
                        </el-form-item>
                        <el-form-item class="form-item" label="法人身份证地址" prop="idcAddress">
                            <el-input class="search-vitem v-address3" v-model="form.idcAddress" placeholder="法人身份证地址"
                                clearable />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="法人身份证有效期" prop="idcPeriod">
                            <el-date-picker format="YYYY-MM-DD" value-format="YYYY-MM-DD" class="search-vitem"
                                v-model="form.idcPeriod" type="date" placeholder="若为长期，则不填写" />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="法人手机号码" prop="corporationTel">
                            <el-input class="search-vitem" v-model="form.corporationTel" placeholder="法人手机号码" clearable />
                        </el-form-item>
                        <el-form-item class="form-item" label="法人是否为公司实控人" prop="isActual">
                            <el-switch v-model="form.isActual" active-value="1" inactive-value="0" active-color="#FF6201"
                                inactive-color="#EEEEEE">
                            </el-switch>
                        </el-form-item>


                    </div>
                </div>

                <div class="app-item">
                    <div class="app-title">联系人</div>
                    <div class="app-cont">

                        <el-form-item class="form-item v50" label="姓名" prop="relationName">
                            <el-input class="search-vitem" v-model="form.relationName" placeholder="姓名" clearable />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="联系电话" prop="relationTel">
                            <el-input class="search-vitem" v-model="form.relationTel" placeholder="联系电话" clearable />
                        </el-form-item>
                        <el-form-item class="form-item v50" label="联系邮箱" prop="relationEmail">
                            <el-input class="search-vitem" v-model="form.relationEmail" placeholder="联系邮箱" clearable />
                        </el-form-item>


                    </div>
                </div>

                <div class="flex-center">
                    <el-button type="primary" @click="submitForm">提交</el-button>
                </div>
            </el-form>
        </div>



    </div>
</template>

<script setup name="Company">
import { ElMessage, ElLoading } from 'element-plus'
import { regionList, IdCardOCRFace, IdCardOCRBack, BusinessLicense, publicList, timestampToTime, happenTimeFun, checkUrl } from "@/api/user/order";
import { Info,save } from "@/api/company/zdf";
const { proxy } = getCurrentInstance();



const data = reactive({
    // 省市区 参数
    CascaderProps: {
        value: 'name',
        label: 'name',
        children: 'list',
    },
    cityOpt: [],
    // 省市区 参数 END
    companyStatusArr: [], //  开业状态
    orgTypeArr: [], // 机构类型
    companyNatureArr: [], //  公司性质



    form: {
		"citycode": null,
    },



    resetForm: {
		"citycode": null,
        "address": "", //公司地址
        "city": "", // 城市
        "province": "", // 省份 
        "companyName": "", //公司名称
        "companyNature": 0, // 公司性质
        "companyStatus": 0, // 开业状态
        "corporationIdc": "", // 法人身份证号码
        "corporationName": "", // 法人姓名
        "corporationTel": "", // 法人手机号
        "creditCode": "", // 社会信用代码
        "establishmentDate": "", // 成立日期
        "idcAddress": "", // 法人身份证地址
        "idcBack": "", // 身份证反面
        "idcFront": "", // 身份证正面
        "idcPeriod": "", // 身份证有效期
        "isActual": 0, // 否为公司实控人
        "license": "", // 营业执照
        "licensePeriod": "", // 营业执照有效期
        "relationEmail": "", // 联系人邮箱
        "relationName": "", // 联系人
        "relationTel": "", // 联系人电话
        "types": "", // 机构类型
    },
    rules: {
        license: [
            { required: true, message: "营业执照不能为空", trigger: "blur" }
        ],
        companyName: [
            { required: true, message: "公司名称不能为空", trigger: "blur" }
        ],
        creditCode: [
            { required: true, message: "统一社会信用代码不能为空", trigger: "blur" }
        ],
        citycode: [
            { required: true, message: "公司地址不能为空", trigger: "blur" }
        ],
        address: [
            { required: true, message: "公司地址不能为空", trigger: "blur" }
        ],
        establishmentDate: [
            { required: true, message: "成立日期不能为空", trigger: "blur" }
        ],
        companyNature: [
            { required: true, message: "公司性质不能为空", trigger: "blur" }
        ],
        types: [
            { required: true, message: "机构类型不能为空", trigger: "blur" }
        ],
        companyStatus: [
            { required: true, message: "开业状态不能为空", trigger: "blur" }
        ],
        idcFront: [
            { required: true, message: "法人身份证正面不能为空", trigger: "blur" }
        ],
        idcBack: [
            { required: true, message: "法人身份证反面不能为空", trigger: "blur" }
        ],

        corporationName: [
            { required: true, message: "法人姓名不能为空", trigger: "blur" }
        ],
        corporationIdc: [
            { required: true, message: "法人身份证号码不能为空", trigger: "blur" }
        ],
        idcAddress: [
            { required: true, message: "法人身份证地址不能为空", trigger: "blur" }
        ],
        corporationTel: [
            { required: true, message: "法人手机号码不能为空", trigger: "blur" },
            { pattern: /^1[3456789]\d{9}$/, message: '法人手机号码格式不正确', trigger: 'blur' }
        ],
        relationName: [
            { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        relationTel: [
            { required: true, message: "联系电话不能为空", trigger: "blur" },
            { pattern: /^1[3456789]\d{9}$/, message: '联系电话不格式不正确', trigger: 'blur' }
        ],
        relationEmail: [
            { required: true, message: "联系邮箱为空", trigger: "blur" },
            { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ],

    }
});

const { form, rules, cityOpt, CascaderProps, companyStatusArr, orgTypeArr, companyNatureArr } = toRefs(data);


// 上传文件
function httpRequest(data, type) {
    var formData = new FormData();
    formData.append("file", data.file);
	formData.append("localType", 0);
    if (type == 1) {
        getBusinessLicense(formData)
    } else if (type == 2) {
        getIdCardOCRFace(formData)
    } else if (type == 3) {
        getIdCardOCRBack(formData)
    }
}
// 所有省市区
function getRegionList() {
    regionList({ threeLevel: 2 }).then(response => {
        var data = response.data;
        cityOpt.value = data;
    });
}


function getPublicList() {
    // 开业状态
    publicList({
        pageNum: 1,
        pageSize: 200,
        dictType: 'company_status',
    }).then(response => {
        var data = response.rows;
        companyStatusArr.value = data;
    });

    // 机构类型
    publicList({
        pageNum: 1,
        pageSize: 200,
        dictType: 'org_type',
    }).then(response => {
        var data = response.rows;
        orgTypeArr.value = data;
    });

    // 公司性质

    publicList({
        pageNum: 1,
        pageSize: 200,
        dictType: 'company_nature',
    }).then(response => {
        var data = response.rows;
        companyNatureArr.value = data;
    });
}

function getInfo() {
    Info({}).then(response => {
        var data = response.data;


        // data.types = data.types.split(',');
        form.value = data;
        form.value.citycode = [data.province, data.city]

        console.log(form.value);

    });
}


// 营业执照识别
function getBusinessLicense(formData) {
    const loadingInstance = ElLoading.service({});
    BusinessLicense(formData).then(response => {
        var data = response.data;
        if (data && data.creditCode) {
            form.value.companyName = data.companyName;
            form.value.creditCode = data.creditCode;
            form.value.license = data.url;

            // 处理日期
            var dateString = data.registrationDate;
            var formattedDate = dateString.replace(/年|月/g, "-").replace(/日/g, "");
            var timedate = new Date(formattedDate);
            var timestamp = timedate.getTime();
            var t = timestampToTime(timestamp);
            form.value.establishmentDate = happenTimeFun(t, 'yyyy-MM-dd');
        }
        loadingInstance.close();
    }).catch(() => {
        loadingInstance.close();
    });
}

function getIdCardOCRFace(formData) {
    const loadingInstance = ElLoading.service({});
    IdCardOCRFace(formData).then(response => {
        var data = response.data;
        if (data && data.idNumber) {
            form.value.corporationIdc = data.idNumber;
            form.value.corporationName = data.name;
            form.value.idcAddress = data.address;
            form.value.idcFront = data.url;
        }
        loadingInstance.close();
    }).catch(() => {
        loadingInstance.close();
    });
}

function getIdCardOCRBack(formData) {
    const loadingInstance = ElLoading.service({});
    IdCardOCRFace(formData).then(response => {
        var data = response.data;
        if (data && data.url) {
            form.value.idcBack = data.url;
        }
        loadingInstance.close();
    }).catch(() => {
        loadingInstance.close();
    });
}



// 提交保存
function submitForm() {

    proxy.$refs["companyRef"].validate(valid => {
        if (valid) {
            var formdata = JSON.parse(JSON.stringify(form.value));
            formdata.province = formdata.citycode[0];
            formdata.city = formdata.citycode[1];
            // formdata.types = formdata.types.join(',');
            const loadingInstance = ElLoading.service({});
            save(formdata).then(response => {
                loadingInstance.close();
                ElMessage({
                    message: '提交成功',
                    type: 'success',
                })
            }).catch(() => {
                loadingInstance.close();
            });
        }
    });
}

getInfo();
getPublicList();
getRegionList();

</script>

<style lang="scss">
.app-container {
    width: 100%;
    background: #f0f2f5;

    .app-page {
        width: 100%;
        background: #FFFFFF;
        padding-bottom: 40px;

        .app-item {
            width: 100%;
        }

        .app-title {
            width: 100%;
            height: 55px;
            line-height: 55px;
            font-style: normal;
            font-weight: 400;
            font-size: 16px;
            color: rgba(0, 0, 0, .85);
            border-bottom: 1px solid #e9e9e9;
            padding: 0 32px;
        }

        .app-cont {
            width: 100%;
            padding: 20px;
        }
    }
}


.form-item {
    width: 100%;

    &.v50 {
        width: 45%;
    }
}

.search-form {
    margin-top: 20px;

    .search-vitem {
        width: 100% !important;

        &.v-address1 {
            width: 30% !important;
        }

        &.v-address2 {
            width: 62% !important;
        }

        &.v-address3 {
            width: 92% !important;
        }
    }
}
</style>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: flex;
    align-items: cen;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #8c939d;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.4s;
}

.avatar-uploader .el-upload:hover {
    border-color: #FF6201;
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>